package com.cuteboy.admin.controller;

import com.cuteboy.admin.service.SysPermissionService;
import com.cuteboy.admin.service.SysRolePermissionService;
import com.cuteboy.admin.service.SysRoleService;
import com.cuteboy.admin.service.SysUserRoleService;
import com.cuteboy.entity.SysPermission;
import com.cuteboy.entity.SysRole;
import com.cuteboy.entity.SysRolePermission;
import com.cuteboy.entity.SysUserRole;
import com.cuteboy.util.Constants;
import com.cuteboy.util.ValidateUtils;
import com.cuteboy.vo.ResponseVO;
import com.google.gson.JsonArray;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("admin/role/permission")
@Controller
public class SysRolePermissionController {
    @Resource
    private SysRolePermissionService sysRolePermissionService;

    /**
     * 获取所有权限
     * 并根据角色名，通过checked字段标出角色已经拥有的去权限
     * @param roleId
     * @return
     */
    @ResponseBody
    @PostMapping("/listPermiByRoleId")
    public ResponseVO selectUserByUsername(Integer roleId) {
        // 获取所有权限
        JsonArray json = sysRolePermissionService.listRolePermissionByRoleId(roleId);
        return new ResponseVO(Constants.ResponseVo.Code.SUCCEESS, Constants.ResponseVo.msg.SUCCEESS, json.toString());
    }

    /**
     * 根据角色 和 权限集合，编辑角色权限
     * @param roleId
     * @param permissionIds
     * @return
     */
    @RequestMapping("roleEditoyPermis")
    @ResponseBody
    public ResponseVO roleEditoyPermis(@RequestParam Integer roleId, @RequestParam String permissionIds){
        // 解析字符串
        String[] permissionIdArr = permissionIds.split(",");
        if (ValidateUtils.isNotNull(permissionIdArr) && permissionIdArr.length > 0){
            // 删除原数据
            sysRolePermissionService.deleteByRoleId(roleId);
            // 载入新数据
            for (String permissionId : permissionIdArr){
                SysRolePermission sysRolePermission = new SysRolePermission();
                sysRolePermission.setRoleId(roleId);
                sysRolePermission.setPermissionCode(permissionId);
                sysRolePermissionService.save(sysRolePermission);
            }
        } else {
            return new ResponseVO(Constants.ResponseVo.Code.ERROR, Constants.ResponseVo.msg.ERROR);
        }

        return new ResponseVO(Constants.ResponseVo.Code.SUCCEESS, Constants.ResponseVo.msg.SUCCEESS);
    }
}
